package times

import (
	"time"
)

type FormatType string

// 定义工具使用的类型常量
const (
	YEAR   FormatType = "year"
	MONTH  FormatType = "month"
	DATE   FormatType = "date"
	HOUR   FormatType = "hour"
	MINUTE FormatType = "minute"
	SECOND FormatType = "second"
)

// 时间工具
type Tool struct {
	time.Time
}

/**
 * 时间周上某天的第一秒
 */
func (t *Tool) FirstSecondOfWeek(weekday ...time.Weekday) *Tool {
	var wishWeekday time.Weekday
	if len(weekday) > 0 {
		wishWeekday = weekday[0]
	} else {
		wishWeekday = time.Sunday // 默认为星期日
	}
	return &Tool{
		Time: t.AddDate(0, 0, int(wishWeekday-t.Weekday())),
	}
}

/**
 * 获取指定时间类型的第一秒
 */
func (t *Tool) FirstSecond(formatType ...FormatType) *Tool {
	var ft FormatType
	if len(formatType) == 0 {
		ft = DATE
	} else {
		ft = formatType[0]
	}
	var tt time.Time
	switch ft {
	case YEAR:
		tt = time.Date(t.Year(), time.January, 1, 0, 0, 0, 0, t.Location())
	case MONTH:
		tt = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
	case HOUR:
		tt = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), 0, 0, 0, t.Location())
	case MINUTE:
		tt = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), 0, 0, t.Location())
	case SECOND:
		tt = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), 0, t.Location())
	case DATE:
		fallthrough
	default:
		tt = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
	}
	return &Tool{
		Time: tt,
	}
}

/**
 * 增加时长
 */
func (t *Tool) Add(d time.Duration) *Tool {
	return &Tool{
		Time: t.Time.Add(d),
	}
}

/**
 * 增加秒数
 */
func (t *Tool) AddSecond(num int) *Tool {
	return t.Add(time.Second * time.Duration(num))
}

/**
 * 增加分钟数
 */
func (t *Tool) AddMinute(num int) *Tool {
	return t.Add(time.Minute * time.Duration(num))
}

/**
 * 增加小时
 */
func (t *Tool) AddHour(num int) *Tool {
	return t.Add(time.Hour * time.Duration(num))
}

/**
 * 增加天数
 */
func (t *Tool) AddDay(num int) *Tool {
	return t.Add(time.Hour * 24 * time.Duration(num))
}

/**
 * 增加月份
 */
func (t *Tool) AddMonth(num int) *Tool {
	tt := &Tool{
		Time: t.AddDate(0, num, 0),
	}
	return tt.FirstSecond(MONTH)
}

/**
 * 增加季度
 */
func (t *Tool) AddSeason(num int) *Tool {
	tt := &Tool{
		Time: t.AddDate(0, num*3, 0),
	}
	return tt.FirstSecond(MONTH)
}

/**
 * 增加年份
 */
func (t *Tool) AddYear(num int) *Tool {
	tt := &Tool{
		Time: t.AddDate(num, 0, 0),
	}
	return tt.FirstSecond(MONTH)
}

/**
 * 增加周
 */
func (t *Tool) AddWeek(num int) *Tool {
	return t.Add(time.Hour * 7 * 24 * time.Duration(num))
}

/**
 * 新建时间工具
 */
func New(t ...time.Time) *Tool {
	var tt time.Time
	if len(t) > 0 {
		tt = t[0]
	} else {
		tt = time.Now()
	}
	return &Tool{
		Time: tt,
	}
}
